import axios from 'axios'
import FormData from 'form-data'
import qs from 'query-string'

axios.defaults.timeout = 100000
// axios.defaults.baseURL = typeof window != 'undefined'?"/":"http://127.0.0.1:8000";
// const BASE_URL = '/stock-data-server' // 测试

axios.interceptors.request.use(config => ({
    ...config,
    // url: '//test-mws.dn8188.com' + config.url
    // url: '//mws.dn8188.com' + config.url
    // url: BASE_URL + config.url
    url: 'http://172.16.11.105:8080/' + config.url

  }),
  (error) => error)

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    alert('接口错误：' + error.response.status)
    return {
      data: {
        data: null,
        state: 'warn',
        message: '请稍后重试',
        code: error.response.status
      }
    }

  }
)

const formatUrl = (url) => {
  let tempUrl = url
  if (url.indexOf('?') > -1) {
    tempUrl += '&_t=' + Date.now()
  } else {
    tempUrl += '?_t=' + Date.now()
  }
  return tempUrl
}

function get(url, params) {
  return new Promise((resolve, reject) => {
    const tempUrl = formatUrl(url)
    axios.get(tempUrl, {
        params
      }).then((response) => {
        resolve(response.data)
        // console.info(`fetch: GET ${tempUrl}  params:${qs.stringify(params || {})} code:${response?.status}}`)
      })
      .catch((error) => reject(error))
  })
}

function post(url, data) {
  return new Promise((resolve, reject) => {
    const tempUrl = formatUrl(url)
    axios.post(tempUrl, data).then(
      (response) => {
        // console.info(`fetch: POST ${tempUrl} params:${qs.stringify(data || {})} code:${response?.status}}`)
        resolve(response.data)
      },
      (err) => reject(err)
    )
  })
}

function form(url, data) {
  return new Promise((resolve, reject) => {
    const tempUrl = formatUrl(url)
    const fromd = new FormData()
    for (const key in data) {
      fromd.append(key, data[key])
    }
    const formHeaders = typeof fromd.getHeaders !== 'function' ? {} : from.getHeaders()
    axios.post(tempUrl, fromd, {
      headers: {
        ...formHeaders
      }
    }).then(
      (response) => {
        console.info(`fetch: form ${tempUrl} params:${qs.stringify(data || {})} code:${response.status}}`)
        resolve(response.data)
      },
      (err) => reject(err)
    )
  })
}

export {
  get,
  post,
  form
}